package business_layer;

import java.util.LinkedList;

import car.manager.BackStageManager;
import car.manager.UserProfile;

//The question is:
//Should all users be loaded into a List and then manipulated within this list?
//This approach means I access the databse in the beginning and in the end
//Would it be more appropriate to be constantly interacting with the database?
public class UserProfileManager {

	private LinkedList<UserProfile> users = new LinkedList<UserProfile>();
	private int currentUserId = -1;
	private UserProfile currentUserProfile = null;

	private BackStageManager backStageManager = null;


	public UserProfileManager(BackStageManager backStageManager) {
		super();
		//is this correct? should a non Activity class be interacting with the Application?
		this.backStageManager = backStageManager;
	}



	public void setUserProfileList(LinkedList<UserProfile> upList) {

		this.users = upList;
	}


	public boolean usersExist(){
		return !users.isEmpty();
	}


	public UserProfile getUser(int id){

		return users.get(id);
	}

	public LinkedList<UserProfile> getUsers() {
		return users;
	}



	public void setUsers(LinkedList<UserProfile> users) {
		this.users = users;
	}



	public int getCurrentUserId() {
		return currentUserId;
	}



	public void setCurrentUserId(int currentUserId) {
		this.currentUserId = currentUserId;
	}







	public UserProfile getCurrentUserProfile() {
		int index = -1;
		//this is needed because the id is not necessarily the index of the user
		//also, I should change this to query the database instead of the list
		if(currentUserId!=-1 && users!=null){
			for(UserProfile u:users){
				if(u.getId()==currentUserId)
					index=users.indexOf(u);
			}

			if(index!=-1){
				return users.get(index);
			}

		}
		return null;

	}



	public void setCurrentUserProfile(int id) {
		this.currentUserId = id;
	}



	public  LinkedList<UserProfile> getAllUsers() {

		return (LinkedList<UserProfile>) users.clone();
	}



	public void addNewUser(String name) {
		
		//temporary solution
		//If I am to start accessing the database, this kind of operations
		//(adding to list and calculating id) become obsolete
		int id = askId();
		UserProfile up = new UserProfile(name);
		up.setId(id);		
		users.add(up);		
		backStageManager.addProfile(up);
		setCurrentUserId(id);
		

	}

	//this method shouldn't exist if there was a database constant connection
	private int askId() {
		if(!users.isEmpty())
			return users.getLast().getId()+1;
		else
			return 1;
	}




}
